import React, { Component } from 'react';
import { List, InputItem, Button, Flex, Toast, Picker, TextareaItem } from 'antd-mobile';
import { createForm } from 'rc-form';

import '../css/skin.css';
import '../css/form.css';
import '../css/apply-form.css';

let dics_arr=[];
let province_arr=[];
let city_arr=[];

// 格式处理函数
function formatData(obj){
  let _datas = {};
  for( let key in obj ){
    let arr = [];
    for( let key2 in obj[key] ){
      let item = { label:obj[key][key2], value:key2};
      arr.push(item);
    }
    _datas[key] = arr;
  }
  return _datas;
}

// 地域处理函数
function formatArea(obj){
  let _areas = [];
  for( let i=0; i<obj.length; i++){
    let item = { label:obj[i].areaName, value:obj[i].areaNo };
    _areas.push(item);
  }
  return _areas;
}

// find Text
function findText(key,obj){
  let _cityName = '';
  for( let i=0; i<obj.length; i++ ){
    if( obj[i].areaNo===key ){
      _cityName = obj[i].areaName;
    }
  }
  //console.log(city_arr,_cityName);
  return _cityName;
}

class applyForm extends Component {
  constructor(propos){
    super(propos);
    //console.log(propos);
    this.state = {
      dics : {},
      area: [],
      province: [],
      city: [],
    }
  }

  loanCreate=()=>{
    var _now = new Date();
    let infos = this.props.form.getFieldsValue();
    let _data = {
      "amount": infos.amount,
      "applyTime": _now,
      "bearStatus": infos.bearStatus[0],
      "cityId": infos.city[0],
      "cityName": findText(infos.city[0],city_arr),
      "companyTypeCode": infos.companyType[0],
      "companyTypeName": dics_arr.COMPANY_TYPE[infos.companyType[0]],
      "contractDate": _now,
      "corporationCode": "N",
      "cycleDays": 22,
      "endTime": _now,
      "houseFundFlag": "Y",
      "identityCardNo": infos.identityCardNo,
      "identityName": infos.identityName,
      "incomeModeCode": infos.incomeMode[0],
      "incomeModeName": dics_arr.INCOME_MODE[infos.incomeMode[0]],
      "loanPeriod": infos.loanPeriod,
      "loanPeriodCode": infos.loanPeriodCode[0],
      "loanPeriodName": dics_arr.LOAN_PERIOD[infos.loanPeriodCode[0]],
      "loanType": dics_arr.LOAN_TYPE[infos.loanType[0]],
      "loanTypeCode": infos.loanType[0],
      "marriageStatus": infos.marriageStatus[0],
      "orderState": "1",
      "phone": infos.phone,
      "privinceId": infos.province[0],
      "privinceName": findText(infos.province[0],province_arr),
      "professionCode": infos.profession[0],
      "professionName": dics_arr.PROFESSION_TYPE[infos.profession[0]],
      "residenceTimeCode": infos.residenceTypeCode[0],
      "residenceTimeName": dics_arr.RESIDENCE_TIME[infos.residenceTypeCode[0]],
      "socialSecurityFlag": "Y",
      "residenceTypeCode": infos.residenceTypeCode[0],
      "residenceTypeName": dics_arr.RESIDENCE_TYPE[infos.residenceTypeCode[0]],
      "worklifeCode": infos.worklife[0],
      "worklifeName": dics_arr.WORK_LIFE[infos.worklife[0]],
      "educationBgCode": infos.educationBgCode[0],
      "educationBgName": dics_arr.EDUCATION_BG[infos.educationBgCode[0]],
    };
    _data = JSON.stringify(_data);
    //console.log(_data);
    //return;
    let formData = new FormData();
    formData.append('loanApply',_data);

    fetch('http://58.220.10.23:8001/api/loanapply/create', {
  	  method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      },
  	  // body: formData,
      /*body: JSON.stringify({
        "loanApply": _data,
      }),*/
      body: _data,
	   }).then(response => response.json())
	   .then(data=>{
        if( data.status==0 ){
          Toast.success('贷款信息发布成功！', 1);
          //history.push('applyForm');
        }else{
          Toast.fail(data.errorMsg, 1);
          console.log(data);
        }
	   }).catch(e => console.log('error: ' + e));

  }

  getCity=(e)=>{
    // ajax get citys
    let _url_area = 'http://58.220.10.23:8001/api/area/query/'+e[0];
    fetch(_url_area,{ method: 'GET', credentials: 'include', }).then(response => response.json())
    .then(dataCity=>{
      city_arr = dataCity;
      let _arr = formatArea(dataCity);
      this.setState({
          city : _arr,
      });
    });
  }

  render() {
    const { getFieldProps } = this.props.form;
    return (
      <div className="skin-blue" style={{marginBottom:'1rem'}}>
        <List>
          <Flex>
            <p className="title">发布借贷信息</p>
          </Flex>
          <Flex>
            <p className="border-color type-name">基本信息</p>
          </Flex>
          <InputItem
            {...getFieldProps('identityName')}
            placeholder="请输入姓名"
            clear
          ></InputItem>
          <InputItem
            {...getFieldProps('identityCardNo')}
            placeholder="请输入身份证号码"
            clear
          ></InputItem>
          <InputItem
            {...getFieldProps('phone')}
            type="phone"
            placeholder="请输入手机号"
            clear
            moneyKeyboardAlign="left"
          ></InputItem>

          <Flex>
            <Flex.Item>
              <Picker data={this.state.province} cols={1} {...getFieldProps('province')}
              onOk={this.getCity}
              className="forss">
                <List.Item arrow="horizontal">请选择省份</List.Item>
              </Picker>
            </Flex.Item>
            <Flex.Item>
              <Picker data={this.state.city} cols={1} {...getFieldProps('city')} className="forss">
                <List.Item arrow="horizontal">市/区</List.Item>
              </Picker>
            </Flex.Item>
          </Flex>

          <Picker data={this.state.dics.RESIDENCE_TIME} cols={1} {...getFieldProps('residenceTimeType',{initialValue: ['1']})} className="forss">
            <List.Item arrow="horizontal">请选择居住时长</List.Item>
          </Picker>
          <Picker data={this.state.dics.RESIDENCE_TYPE} cols={1} {...getFieldProps('residenceTypeCode',{initialValue: ['1']})} className="forss">
            <List.Item arrow="horizontal">请选择住房信息</List.Item>
          </Picker>
          <Picker data={this.state.dics.EDUCATION_BG} cols={1} {...getFieldProps('educationBgCode',{initialValue: ['3']})} className="forss">
            <List.Item arrow="horizontal">请选择学历</List.Item>
          </Picker>
          <Picker data={this.state.dics.MARRIAGE_STATUS} cols={1} {...getFieldProps('marriageStatus',{initialValue: ['N']})} className="forss">
            <List.Item arrow="horizontal">请选择婚姻状况</List.Item>
          </Picker>
          <Picker data={this.state.dics.BEAR_STATUS} cols={1} {...getFieldProps('bearStatus',{initialValue:['U']})} className="forss">
            <List.Item arrow="horizontal">请选择生育状况</List.Item>
          </Picker>

          <Flex>
            <p className="border-color type-name">职业信息</p>
          </Flex>
          <Picker data={this.state.dics.PROFESSION_TYPE} cols={1} {...getFieldProps('profession',{initialValue:['4']})} className="forss">
            <List.Item arrow="horizontal">请选择职业</List.Item>
          </Picker>
          <Picker data={this.state.dics.COMPANY_TYPE} cols={1} {...getFieldProps('companyType',{initialValue: ['2']})} className="forss">
            <List.Item arrow="horizontal">请选择公司性质</List.Item>
          </Picker>
          <Picker data={this.state.dics.WORK_LIFE} cols={1} {...getFieldProps('worklife',{initialValue: ['2']})} className="forss">
            <List.Item arrow="horizontal">请选择工作年限</List.Item>
          </Picker>

          <Picker data={this.state.dics.INCOME_MODE} cols={1} {...getFieldProps('incomeMode',{initialValue: ['1']})} className="forss">
            <List.Item arrow="horizontal">请选择收入流水</List.Item>
          </Picker>

          <Flex>
            <p className="border-color type-name">借款信息</p>
          </Flex>
          <Picker data={this.state.dics.LOAN_TYPE} cols={1} {...getFieldProps('loanType',{initialValue: ['0']})} className="forss">
            <List.Item arrow="horizontal">请选择贷款类型</List.Item>
          </Picker>
          <InputItem
            {...getFieldProps('amount')}
            type="money"
            placeholder="请输入借款金额"
            clear
            moneyKeyboardAlign="left"
          ></InputItem>
          <Flex>
            <Flex.Item>
              <InputItem
                {...getFieldProps('loanPeriod')}
                type="number"
                placeholder="请输入借款周期"
                clear
                moneyKeyboardAlign="left"
              ></InputItem>
            </Flex.Item>
            <Flex.Item>
              <Picker data={this.state.dics.LOAN_PERIOD} cols={1} {...getFieldProps('loanPeriodCode',{initialValue: ['2']})} className="forss">
                <List.Item arrow="horizontal">请选择单位</List.Item>
              </Picker>
            </Flex.Item>
          </Flex>


          <Flex>
            <p className="border-color type-name">其他备注</p>
          </Flex>
          <TextareaItem
            {...getFieldProps('remark')}
            rows={5}
            count={100}
          />

          <List.Item>
            <Button type="primary" onClick={this.loanCreate}>申请</Button>
          </List.Item>

        </List>
      </div>
    );
  }

  componentDidMount(){

    let _dickeys = 'RESIDENCE_TIME,RESIDENCE_TYPE,EDUCATION_BG,BEAR_STATUS,PROFESSION_TYPE,COMPANY_TYPE,WORK_LIFE,INCOME_MODE,LOAN_TYPE,MARRIAGE_STATUS,LOAN_PERIOD';
    let _url = 'http://58.220.10.23:8001/api/dic/queryDicByIndexkeys?indexkeys[]='+_dickeys;
    fetch( _url, {
  	  method: 'GET',
      credentials: 'include',
	   }).then(response => response.json())
	   .then(data=>{
        dics_arr = data;
        data = formatData(data);
        this.setState({
            dics : data
        });
        console.log(this.state.dics);
	   }).catch(e=>{ console.log(e); this.props.history.push("applyLogin"); });

    // ajax get area info
    let _url_area = 'http://58.220.10.23:8001/api/area/query/0';
    fetch(_url_area,{ method: 'GET', credentials: 'include', }).then(response => response.json())
    .then(dataArea=>{
      province_arr = dataArea;
      let _arr = formatArea(dataArea);
      this.setState({
          province: _arr
      });
      //console.log(this.state.privince);
    });
  }
}
const _applyForm = createForm()(applyForm);
export default _applyForm;
